//
//  HEContaintView.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/10/22.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEContaintView.h"
#import "HXPhotoPicker.h"

@interface HEContaintView ()<HXPhotoViewDelegate>

/**  照片视图  */
@property (nonatomic, strong) HXPhotoView *photoView;

/**  照片管理  */
@property (nonatomic, strong) HXPhotoManager *manager;

/** 必须加上判断，否则会出现重复添加图片 */
@property (nonatomic, assign) BOOL hasShow;

@property (nonatomic, strong) NSMutableArray *photoHeights;
@property (copy, nonatomic) NSArray *imageRequestIds;

@end

@implementation HEContaintView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = UIColor.orangeColor;
    }
    return self;
}

- (void)setupUI {
    
    if (self.photoView) {
        return;
    }
    
    [self addSubview:self.photoView];
 
    [self.photoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self).mas_offset(0);
        make.left.mas_equalTo(self).mas_offset(0);
        make.right.mas_equalTo(self).mas_offset(0);
        make.height.mas_equalTo(0);
    }];
 
}

- (void)setPhotoNamesArray:(NSArray *)photoNamesArray {
    _photoNamesArray = photoNamesArray;
    
//    if (_hasShow) {
//        return;
//    }
    
//    if(photoNamesArray.count == 0) {
//        return;
//    }
    
    [self setupUI];

  
    // 这些操作需要放在manager赋值的后面，不然会出现重用..
    self.manager.configuration.albumShowMode = HXPhotoAlbumShowModePopup;
    self.photoView.previewStyle = HXPhotoViewPreViewShowStyleDark;
    self.photoView.collectionView.editEnabled = NO;
    self.photoView.hideDeleteButton = YES;
    self.photoView.showAddCell = NO;
    NSMutableArray *customAssetModels = @[ ].mutableCopy;

    for (NSString *url in photoNamesArray) {
                  HXCustomAssetModel *assetModel3 = [HXCustomAssetModel assetWithNetworkImageURL:[NSURL URLWithString:url] selected:YES];
        
        [customAssetModels addObject:assetModel3];
    }
        

      [self.manager addCustomAssetModel: customAssetModels];
    //    model.addCustomAssetComplete = YES;

    __weak typeof(self) weakself = self;

    HXWeakSelf
    self.manager.configuration.previewRespondsToLongPress = ^(UILongPressGestureRecognizer *longPress, HXPhotoModel *photoModel, HXPhotoManager *manager, HXPhotoPreviewViewController *previewViewController) {
        HXPhotoBottomViewModel *saveModel = [[HXPhotoBottomViewModel alloc] init];
        saveModel.title = @"保存";
        saveModel.customData = photoModel.tempImage;
        [HXPhotoBottomSelectView showSelectViewWithModels:@[saveModel] selectCompletion:^(NSInteger index, HXPhotoBottomViewModel * _Nonnull model) {

            if (photoModel.subType == HXPhotoModelMediaSubTypePhoto) {
                if (photoModel.cameraPhotoType == HXPhotoModelMediaTypeCameraPhotoTypeNetWork ||
                    photoModel.cameraPhotoType == HXPhotoModelMediaTypeCameraPhotoTypeNetWorkGif) {
                    NSSLog(@"需要自行保存网络图片");
                    
                    [weakself toSaveImage:photoModel.networkPhotoUrl];
                    return;
                }
            }else if (photoModel.subType == HXPhotoModelMediaSubTypeVideo) {
                if (photoModel.cameraVideoType == HXPhotoModelMediaTypeCameraVideoTypeNetWork) {
                    NSSLog(@"需要自行保存网络视频");
                    return;
                }
            }
            [previewViewController.view hx_showLoadingHUDText:@"保存中"];
            if (photoModel.subType == HXPhotoModelMediaSubTypePhoto) {
                [HXPhotoTools savePhotoToCustomAlbumWithName:weakSelf.manager.configuration.customAlbumName photo:model.customData location:nil complete:^(HXPhotoModel * _Nullable model, BOOL success) {
                    [previewViewController.view hx_handleLoading];
                    if (success) {
                        [previewViewController.view hx_showImageHUDText:@"保存成功"];
                    }else {
                        [previewViewController.view hx_showImageHUDText:@"保存失败"];
                    }
                }];
            }else if (photoModel.subType == HXPhotoModelMediaSubTypeVideo) {
                if (photoModel.cameraVideoType == HXPhotoModelMediaTypeCameraVideoTypeNetWork) {
                    [[HXPhotoCommon photoCommon] downloadVideoWithURL:photoModel.videoURL progress:nil downloadSuccess:^(NSURL * _Nullable filePath, NSURL * _Nullable videoURL) {
                        [HXPhotoTools saveVideoToCustomAlbumWithName:nil videoURL:filePath location:nil complete:^(HXPhotoModel * _Nullable model, BOOL success) {
                            [previewViewController.view hx_handleLoading];
                            if (success) {
                                [previewViewController.view hx_showImageHUDText:@"保存成功"];
                            }else {
                                [previewViewController.view hx_showImageHUDText:@"保存失败"];
                            }
                        }];
                    } downloadFailure:^(NSError * _Nullable error, NSURL * _Nullable videoURL) {
                        [previewViewController.view hx_handleLoading];
                        [previewViewController.view hx_showImageHUDText:@"保存失败"];
                    }];
                    return;
                }
                [HXPhotoTools saveVideoToCustomAlbumWithName:nil videoURL:photoModel.videoURL location:nil complete:^(HXPhotoModel * _Nullable model, BOOL success) {
                    [previewViewController.view hx_handleLoading];
                    if (success) {
                        [previewViewController.view hx_showImageHUDText:@"保存成功"];
                    }else {
                        [previewViewController.view hx_showImageHUDText:@"保存失败"];
                    }
                }];
            }
        } cancelClick:nil];
    };
        
    [self.photoView refreshView];
    _hasShow = true;
    [self.photoView setNeedsLayout];
    [self.photoView layoutIfNeeded];
}
- (void)toSaveImage:(NSURL *)url {
 
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    
    if ([manager cacheKeyForURL:url]) {
       [[manager imageCache] queryImageForKey:url.absoluteString options:SDWebImageFromCacheOnly context:nil completion:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
           // 保存图片到相册中
           UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        }];
        return;
    }
    else {
        //从网络下载图片
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *img = [UIImage imageWithData:data];
        // 保存图片到相册中
        UIImageWriteToSavedPhotosAlbum(img,self, @selector(image:didFinishSavingWithError:contextInfo:),nil);
    }
}
//保存图片完成之后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo {
    if (error != NULL) {
        [Dialog toast:@"图片保存失败" delay:2.0];
    }
    else  // No errors
    {
        [Dialog toast:@"图片保存成功" delay:2.0];
    }
}



- (void)photoView:(HXPhotoView *)photoView changeComplete:(NSArray<HXPhotoModel *> *)allList photos:(NSArray<HXPhotoModel *> *)photos videos:(NSArray<HXPhotoModel *> *)videos original:(BOOL)isOriginal {
    if (photoView == self.photoView) {
//        self.model.endCameraList = self.manager.afterCameraArray.mutableCopy;
//        self.model.endCameraPhotos = self.manager.afterCameraPhotoArray.mutableCopy;
//        self.model.endCameraVideos = self.manager.afterCameraVideoArray.mutableCopy;
//        self.model.endSelectedCameraList = self.manager.afterSelectedCameraArray.mutableCopy;
//        self.model.endSelectedCameraPhotos = self.manager.afterSelectedCameraPhotoArray.mutableCopy;
//        self.model.endSelectedCameraVideos = self.manager.afterSelectedCameraVideoArray.mutableCopy;
//        self.model.endSelectedList = self.manager.afterSelectedArray.mutableCopy;
//        self.model.endSelectedPhotos = self.manager.afterSelectedPhotoArray.mutableCopy;
//        self.model.endSelectedVideos = self.manager.afterSelectedVideoArray.mutableCopy;
//        self.model.iCloudUploadArray = self.manager.afterICloudUploadArray.mutableCopy;
    }
}
- (void)photoView:(HXPhotoView *)photoView updateFrame:(CGRect)frame {
    
    if (_photoNamesArray.count == 0) {
        return;
    }
    
    if (photoView != self.photoView) {
        return;
    }
////    if (frame.size.height == self.model.photoViewHeight) {
//        for (NSLayoutConstraint *heightConstraint in self.photoView.constraints) {
//            if (heightConstraint.firstAttribute != NSLayoutAttributeHeight) {
//                continue;
//            }
//            if (heightConstraint.constant != frame.size.height) {
//                // 如果高度约束不对，在这里修正高度的约束
//                heightConstraint.constant = frame.size.height;
//                return;
//            }
//        }
////        return;
////    }
// 
    [self.photoView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(frame.size.height);
    }];
 
    if (self.photoViewChangeHeightBlock) {
        
        self.photoViewChangeHeightBlock(frame.size.height);

//        if (!_hasShow) {
//                 self.photoViewChangeHeightBlock(102);
//
//        }else {
//            self.photoViewChangeHeightBlock(202);
//
//        }
    }
}


- (HXPhotoManager *)manager {
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhotoAndVideo];
        _manager.configuration.selectTogether = YES;
    }
    return _manager;
}

- (HXPhotoView *)photoView {
    if (!_photoView) {
        _photoView = [[HXPhotoView alloc] initWithFrame:CGRectMake(12, 0, [UIScreen mainScreen].bounds.size.width - 24, 0) manager:self.manager];
        _photoView.delegate = self;
    }
    return _photoView;
}

@end
